﻿using System;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using DAL;
using Entity;
using Newtonsoft.Json.Linq;
using NLog;
using System.Drawing.Imaging;
using System.Linq;
using System.Xml;
public partial class Admin_AddArticalsIframe : ParentPage
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                ManageCategory objManageCategory = new ManageCategory();
                FormsFunction.BindDDL(ref ddlArticalsCategory, objManageCategory.GetAllCategory(), "CatName", "Cat_ID");
                Users objUser = (Users)Session["Admin"];
                hfUserID.Value = objUser.UserID;
                if (Request.UrlReferrer.AbsoluteUri.IndexOf("ArticlesID=") >= 0)
                {

                    ManageArticls objDALManageCategory = new ManageArticls();
                    string sQueryString = HttpContext.Current.Request.UrlReferrer.ToString();
                    var result = sQueryString.Substring(sQueryString.LastIndexOf('=') + 1);
                    Articls objArticls = objDALManageCategory.GetArticlsInfo(result);
                    txtArticlsTitle.Text = objArticls.ArticlsTitle;
                    //txtArticls_SmallDescription.Text = objArticls.ArticlsSmallDescription;
                    editor.InnerText = objArticls.ArticlsFullDescription;
                    txtArticlsVedioCode.Text = objArticls.ArticlsVedio;
                    ddlArticalsCategory.SelectedValue = objArticls.CategoryID.ToString();
                    ddlIsFeatures.SelectedValue = objArticls.IsFeatures.ToString();
                    hfImageFull.Value = objArticls.ArticlsImage;
                    ArticlsID.Value = result;
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Error("Admin_AddArticalsIframe:::Page_Load:::" + ex.Message);
        }
    }

    private void ErrorResult()
    {
        Response.Clear();
        Response.StatusCode = 404;
        Response.End();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            Articls objArticls = new Articls();
            ManageArticls objManageArticls = new ManageArticls();
            objArticls.ArticlsTitle = txtArticlsTitle.Text;
            if (editor.InnerText.Length > 100)
            {
                objArticls.ArticlsSmallDescription = editor.Value.Substring(0, 100).Replace("<p style=\"direction: rtl;\">", "").Replace("<p>", "").Replace("</p>", "");
            }
            else
            {
                objArticls.ArticlsSmallDescription = editor.Value.Substring(0, editor.InnerText.Length - 1).Replace("<p style=\"direction: rtl;\">", "").Replace("<p>", "").Replace("</p", "");
            }
            objArticls.CategoryID = Convert.ToInt16(ddlArticalsCategory.SelectedValue);
            objArticls.IsFeatures = Convert.ToInt16(ddlIsFeatures.SelectedValue);
            objArticls.ArticlsStatus = 1;
            if (fuArticlsImage2.HasFile)
            {
                string newname = "LiveKora_" + txtArticlsTitle.Text.Replace(" ", "-");
                string extension = Path.GetExtension(fuArticlsImage2.PostedFile.FileName);
                string sFile2Path = Server.MapPath("~/ArticalsImage/Full/" + newname + extension);
                fuArticlsImage2.SaveAs(sFile2Path);
                CompressJpeg(sFile2Path, 55);
                objArticls.ArticlsImage = "../ArticalsImage/Full/" + newname + extension;
                objArticls.ArticlsThumb = "../ArticalsImage/Full/" + newname + extension;
            }
            else
            {
                if (string.IsNullOrEmpty(hfImageFull.Value))
                {
                    objArticls.ArticlsImage = "null";
                    objArticls.ArticlsThumb = "null";
                }
                else
                {
                    objArticls.ArticlsImage = hfImageFull.Value;
                    objArticls.ArticlsThumb = hfImageFull.Value;
                }
            }
            objArticls.PublisherName = hfUserID.Value;
            objArticls.ArticlsFullDescription = editor.InnerText;
            objArticls.ArticlsVedio = txtArticlsVedioCode.Text;

            if (!string.IsNullOrEmpty(ArticlsID.Value))
            {
                objArticls.ArticlsID = Convert.ToInt32(ArticlsID.Value);
                int nReturnValue = objManageArticls.EditArticlsInfo(objArticls);
                if (nReturnValue == 1)
                    tr_UserMessage.InnerHtml = "Edit Articals Successfully";
                else
                    tr_UserMessage.InnerHtml = "you have issues please contact the system support";
            }
            else
            {
                int nReturnValue = (int)objManageArticls.AddNewArticls(objArticls);
                if (nReturnValue != 0)
                {
                    SiteMapGenerater(string.Format("http://www.livekora.net/Articles/{0}/{1}", nReturnValue, txtArticlsTitle.Text), DateTime.Now.ToString(), "daily", "0.69");
                    tr_UserMessage.InnerHtml = "Add Articals Successfully";
                    txtArticlsTitle.Text = string.Empty;
                    txtArticlsVedioCode.Text = string.Empty;
                    editor.InnerText = string.Empty;
                    ddlIsFeatures.SelectedIndex = -1;
                    ddlArticalsCategory.SelectedIndex = -1;
                    txtArticlsTitle.Focus();
                }
                else
                {
                    tr_UserMessage.InnerHtml = "you have issues please contact the system support";
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Error("Admin_AddArticalsIframe:::btnSubmit_Click:::" + ex.Message);
            throw;
        }
    }

    public void CompressJpeg(string path, int quality)
    {
        FileInfo objFileInfo;
        using (System.Drawing.Image source = System.Drawing.Image.FromFile(path))
        {
            ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().First(c => c.MimeType == "image/jpeg");
            EncoderParameters parameters = new EncoderParameters(3);
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 40L);
            parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ScanMethod, (int)EncoderValue.ScanMethodInterlaced);
            parameters.Param[2] = new EncoderParameter(System.Drawing.Imaging.Encoder.RenderMethod, (int)EncoderValue.RenderProgressive);
            objFileInfo = new FileInfo(path);
            source.Save(Server.MapPath("~/ArticalsImage/x/") + objFileInfo.Name, codec, parameters);
        }

        File.Delete(Server.MapPath("~/ArticalsImage/Full/") + objFileInfo.Name);
        File.Move(Server.MapPath("~/ArticalsImage/x/") + objFileInfo.Name, Server.MapPath("~/ArticalsImage/Full/") + objFileInfo.Name);

    }


    protected void btnGetAllUserTwiite_Click(object sender, EventArgs e)
    {
        try
        {
            findUserTwitter();
        }
        catch (Exception ex)
        {
            _logger.Error("Admin_AddArticalsIframe:::btnGetAllUserTwiite_Click:::" + ex.Message);
        }
    }

    public void SiteMapGenerater(string loc, string lastmod, string changefreq, string priority)
    {
        //_root root for new element
        // path sitemap physical location eg sitemap.xml  (at root)

        string path = "../sitemap/sitemap.xml";
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Current.Server.MapPath(path));
            XmlNode snippet = doc.CreateNode(XmlNodeType.Element, "url", doc.DocumentElement.NamespaceURI);
            XmlNode _loc = doc.CreateNode(XmlNodeType.Element, "loc", doc.DocumentElement.NamespaceURI);

            _loc.InnerText = HttpUtility.UrlDecode(loc);
            XmlNode _lastmod = doc.CreateNode(XmlNodeType.Element, "lastmod", doc.DocumentElement.NamespaceURI);
            _lastmod.InnerText = DateTime.Now.ToString("yyyy-MM-dd");
            XmlNode _changefreq = doc.CreateNode(XmlNodeType.Element, "changefreq", doc.DocumentElement.NamespaceURI);
            _changefreq.InnerText = changefreq;
            XmlNode _priority = doc.CreateNode(XmlNodeType.Element, "priority", doc.DocumentElement.NamespaceURI);
            _priority.InnerText = priority;
            snippet.AppendChild(_loc);
            snippet.AppendChild(_lastmod);
            snippet.AppendChild(_changefreq);
            snippet.AppendChild(_priority);
            int cnt = doc.ChildNodes.Count;
            int g = snippet.Attributes.Count;
            doc.ChildNodes.Item(cnt - 1).AppendChild(snippet);
            doc.Save(HttpContext.Current.Server.MapPath(path));
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected string GetThumnb(string sYoutubeURL)
    {
        try
        {
            string[] parts = sYoutubeURL.Split(new[] { "=" }, int.MaxValue, StringSplitOptions.None);
            return parts[1];
        }
        catch (Exception)
        {
            return "null";
        }
    }

    public void findUserTwitter()
    {
        try
        {
            string oauth_token = ConfigurationManager.AppSettings["AauthToken"].ToString();
            string oauth_token_secret = ConfigurationManager.AppSettings["OauthTokenSecret"].ToString();
            string oauth_consumer_key = ConfigurationManager.AppSettings["OauthConsumerKey"].ToString();
            string oauth_consumer_secret = ConfigurationManager.AppSettings["OauthConsumerSecret"].ToString();
            string URL = ConfigurationManager.AppSettings["APITwiiterURL"].ToString();
            string SureName = ConfigurationManager.AppSettings["SureName"].ToString();
            var oauth_version = "1.0";
            var oauth_signature_method = "HMAC-SHA1";
            var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
            var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                            "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";
            var baseString = string.Format(baseFormat,
                                        oauth_consumer_key,
                                        oauth_nonce,
                                        oauth_signature_method,
                                        oauth_timestamp,
                                        oauth_token,
                                        oauth_version,
                                        Uri.EscapeDataString(SureName)
                                        );
            baseString = string.Concat("GET&", Uri.EscapeDataString(URL), "&", Uri.EscapeDataString(baseString));
            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret));
            string oauth_signature = string.Empty;
            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }
            var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                               "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                               "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
                               "oauth_version=\"{6}\"";
            var authHeader = string.Format(headerFormat,
                                    Uri.EscapeDataString(oauth_nonce),
                                    Uri.EscapeDataString(oauth_signature_method),
                                    Uri.EscapeDataString(oauth_timestamp),
                                    Uri.EscapeDataString(oauth_consumer_key),
                                    Uri.EscapeDataString(oauth_token),
                                    Uri.EscapeDataString(oauth_signature),
                                    Uri.EscapeDataString(oauth_version)
                            );
            ServicePointManager.Expect100Continue = false;
            var postBody = "q=" + Uri.EscapeDataString(SureName);//
            URL += "?" + postBody;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Headers.Add("Authorization", authHeader);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            var response = (HttpWebResponse)request.GetResponse();
            var reader = new StreamReader(response.GetResponseStream());
            var objText = reader.ReadToEnd();
            string html = string.Empty;
            Articls objArticls = new Articls();
            ManageArticls objManageArticls = new ManageArticls();
            JArray jsonDat = JArray.Parse(objText);
            for (int x = 0; x < jsonDat.Count; x++)
            {
                //html += jsonDat[x]["id"].ToString() + "<br/>";
                html += jsonDat[x]["text"].ToString() + "<br/>";
                // html += jsonDat[x]["name"].ToString() + "<br/>";
                //html += jsonDat[x]["created_at"].ToString() + "<br/>";
                objArticls.CategoryID = 9;
                objArticls.ArticlsTitle = jsonDat[x]["text"].ToString();
                objArticls.ArticlsSmallDescription = jsonDat[x]["text"].ToString();
                objArticls.ArticlsFullDescription = jsonDat[x]["text"].ToString();
                objArticls.ArticlsImage = "null";
                objArticls.ArticlsVedio = "null";
                objArticls.PublisherName = hfUserID.Value;
                objManageArticls.AddNewArticls(objArticls);
            }
            oauth_token = string.Empty;
            oauth_token_secret = string.Empty;
            oauth_consumer_key = string.Empty;
            oauth_consumer_secret = string.Empty;
            URL = string.Empty;
            SureName = string.Empty;
            oauth_version = string.Empty;
            oauth_signature_method = string.Empty;
            oauth_nonce = string.Empty;
            oauth_timestamp = string.Empty;
            baseFormat = string.Empty;
            baseString = string.Empty;
            compositeKey = string.Empty;
            oauth_signature = string.Empty;
            html = string.Empty;
        }
        catch (Exception twit_error)
        {
            _logger.Error("_Default:::findUserTwitter:::" + twit_error.Message);
        }
    }
}